<?

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
#	FILE:			includes/files.php
#	FUNCTION:		File-handling functions
#	AUTHOR:			Cameron Morrow
#	CREATED:		26/07/2005
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


/**
 * getSubDirectories() gets an array of sub-directories of a passed directory
 *
 * @param directory_path is the path to start at
 *
 * @return an array of directory names
*/
function getSubDirectories($directory_path = "") {

	# Create array
	$directory_array = array();

	# Try opening
	if (@$dir = opendir($directory_path)) {

		# Read the directory
		while ((@$file = readdir($dir)) !== false) {

			# If it's a directory
			if (@$subdir = opendir($directory_path . $file) && $file != "." && $file != "..") {

				$directory_array[] = "" . $file;
			}
		}
	} else {

		addError("<p>getSubDirectories(): could not read directory path:<code>" . $directory_path . "</code></p>", 3);
	}

	# Return
	return $directory_array;
}


/**
 * getFiles() gets the files in a passed directory
*/
function getFiles($directory_path = "") {

	# Create array
	$file_array = array();

	# Try opening
	if (@$dir = opendir($directory_path)) {

		# Read the next file
		while ((@$file = readdir($dir)) !== false) {

			# If it's a file
			if ((@$subdir = opendir($directory_path . $file)) === false && $file != "." && $file != "..") {

				$file_array[] = "" . $file;
			}
		}
	} else {

		addError("<p>getFiles(): could not read directory path:<code>" . $directory_path . "</code></p>", 3);
	}

	# Return
	return $file_array;
}


/**
 * createDirectory() creates a directory
 *
 * @param directory_path is the path to where the directory should be made
 * @param directory_name is the name of the directory
 *
 * @return the success of the operation
*/
function createDirectory($directory_path = "", $directory_name = "unnamed") {

	# Try opening the path
	if (@$dir = opendir($directory_path)) {

		# Create the directory
		if (@mkdir($directory_path . $directory_name)) {

			return true;

		} else {

			addError("<p>createDirectory(): could not create directory:<code>" . $directory_path . $directory_name . "</code></p>", 2);

			return false;
		}
	} else {

		addError("<p>createDirectory(): could not read directory path:<code>" . $directory_path . "</code></p>", 3);

		return false;
	}
}


/**
 * renameDirectory() renames a directory
 *
 * @param directory_path is the path to the directory
 * @param old_directory_name is the old name of the directory
 * @param new_directory_name is the new name of the directory
 *
 * @return the success of the operation
*/
function renameDirectory($directory_path = "", $old_directory_name = "", $new_directory_name = "") {

	# Check old directory exists
	if (@$dir = opendir($directory_path . $old_directory_name)) {

		# Close
		@closedir($dir);

		# Check new directory name DOESN'T exist
		if ((@$dir = opendir($directory_path . $new_directory_name)) === false) {

			# Close (shouldn't be needed, but better to be safe)
			@closedir($dir);

			# Try renaming
			if (@rename($directory_path . $old_directory_name, $directory_path . $new_directory_name) !== false) {

				return true;
			} else {

				addError("<p>renameDirectory(): An error occured during the rename of:<code>" . $directory_path . $old_directory_name . " =&gt; " . $directory_path . $new_directory_name . "</code></p>", 2);

				return false;
			}

		} else {

			addError("<p>renameDirectory(): There is already a directory with the new name:<code>" . $directory_path . $new_directory_name . "</code></p>", 3);

			return false;
		}


	} else {

		addError("<p>renameDirectory(): Could not find directory:<code>" . $directory_path . $old_directory_name . "</code></p>", 3);

		return false;
	}
}


/**
 * deleteDirectory() deletes a directory
 *
 * @param directory_path is the path to the directory
 * @param directory_name is the name of the directory
 *
 * @return the success of the operation
*/
function deleteDirectory($directory_path = "", $directory_name) {

	# Check it exists
	if (($directory_path != "" && $directory_name != "") && (@$dir = opendir($directory_path . $directory_name))) {

		# Delete files
		while ((@$file = readdir($dir)) !== false) {

			# If it's a file
			if ($file != "." && $file != "..") {

				# Delete
				deleteFile($directory_path . $directory_name, $file);
			}
		}

		# Close dir
		closedir($dir);

		# Try to delete
		if (rmdir($directory_path . $directory_name)) {

			# OK
			return true;

		} else {

			# Error
			addError("<p>deleteDirectory(): An error occured with<code>rmdir(" . $directory_path . $directory_name . ")</code></p>", 2);

			# Fail
			return false;
		}
	} else {
		
		# Error
		addError("<p>deleteDirectory(): The directory<code>" . $directory_path . $directory_name . "</code>could not be found.</p>", 3);

		# Fail
		return false;
	}
}


/**
 * deleteFile() deletes a file
*/
function deleteFile($directory_path = "", $file_name = "") {

	# Check file exists
	if (@file_exists($directory_path . "/" . $file_name)) {

		# Delete
		if (@unlink($directory_path . "/" . $file_name)) {

			# OK
			return true;

		} else {

			# Error
			addError("<p>deleteFile(): File could not be deleted:<code>" . $directory_path . "/" . $file_name . "</code></p>", 2);

			# Fail
			return false;
		}
	} else {

		# Error
		addError("<p>deleteFile(): File does not exist:<code>" . $directory_path . "/" . $file_name . "</code></p>", 3);

		# Fail
		return false;
	}
}


/**
 * getSectionNames() gets an array of current section names (the directories at the top level of the page minus the assets, includes, etc
 *
 * @return an array of section names
*/
function getSectionNames() {

	# Globals
	global $NON_SECTION_FOLDERS;

	# Get top-level directories
	$directory_array = getSubDirectories("../");

	foreach ($NON_SECTION_FOLDERS as $non_section_folder_name) {

		# Get index
		$folder_index = findInArray($directory_array, $non_section_folder_name);

		if ($folder_index !== false) {

			# Cut out
			$directory_array = array_merge(array_slice($directory_array, 0, $folder_index), array_slice($directory_array, $folder_index + 1));
		}

	}

	return $directory_array;
}

function getGallaryFiles($get_details = false, $search_term = ""){
	
	# Global
	global $FILE_TYPES_ARRAY;

	# Array of sorted files
	$sorted_files_array = array();

	# Create empty arrays to hold files in
	foreach ($FILE_TYPES_ARRAY as $key => $value) {
		$sorted_files_array[] = array();
	}

	# Get array of files
	$uploaded_files = getFiles("../front/gallery/");

	# Cycle through, sorting
	foreach ($uploaded_files as $file_name) {

		# Get extension
		$file_extension = strtolower(substr($file_name, strrpos($file_name, ".") + 1));

		# Find type
		$file_type = count($FILE_TYPES_ARRAY);

		# For each group of types
		foreach ($FILE_TYPES_ARRAY as $type_index => $file_types) {

			# If it's in this group
			if (findInArray($file_types, $file_extension) !== false) {
				$file_type = $type_index;
			}
		}

		# Check search
		if ($search_term != "") {
			$search_ok = false;

			if (strpos(strtolower($file_name), strtolower($search_term)) !== false) {
				$search_ok = true;
			}
		} else {
			$search_ok = true;
		}

		if ($search_ok) {

			# If getting details
			if ($get_details) {

				# Get details about the file
				$file_size = filesize("../front/gallery/" . $file_name);

				# See if thumbnail exists
				$thumbnail_exists = file_exists("../front/gallery/" . $file_name);

				# Add to sorted files
				$sorted_files_array[$file_type][] = array("name" => $file_name, "size" => $file_size, "thumbnail" => $thumbnail_exists);

			} else {

				# Add to sorted files
				$sorted_files_array[$file_type][] = $file_name;
			}
		}
	}

	# Return
	return $sorted_files_array;
}

/**
 * getUploadedFiles gets an array of files in the Uploads directory, sorted into images, documents, and other
*/
function getUploadedFiles($get_details = false, $search_term = "") {

	# Global
	global $FILE_TYPES_ARRAY;

	# Array of sorted files
	$sorted_files_array = array();

	# Create empty arrays to hold files in
	foreach ($FILE_TYPES_ARRAY as $key => $value) {
		$sorted_files_array[] = array();
	}

	# Get array of files
	$uploaded_files = getFiles("../assets/uploads/");

	# Cycle through, sorting
	foreach ($uploaded_files as $file_name) {

		# Get extension
		$file_extension = strtolower(substr($file_name, strrpos($file_name, ".") + 1));

		# Find type
		$file_type = count($FILE_TYPES_ARRAY);

		# For each group of types
		foreach ($FILE_TYPES_ARRAY as $type_index => $file_types) {

			# If it's in this group
			if (findInArray($file_types, $file_extension) !== false) {
				$file_type = $type_index;
			}
		}

		# Check search
		if ($search_term != "") {
			$search_ok = false;

			if (strpos(strtolower($file_name), strtolower($search_term)) !== false) {
				$search_ok = true;
			}
		} else {
			$search_ok = true;
		}

		if ($search_ok) {

			# If getting details
			if ($get_details) {

				# Get details about the file
				$file_size = filesize("../assets/uploads/" . $file_name);

				# See if thumbnail exists
				$thumbnail_exists = file_exists("../assets/uploads/thumbnails/" . $file_name);

				# Add to sorted files
				$sorted_files_array[$file_type][] = array("name" => $file_name, "size" => $file_size, "thumbnail" => $thumbnail_exists);

			} else {

				# Add to sorted files
				$sorted_files_array[$file_type][] = $file_name;
			}
		}
	}

	# Return
	return $sorted_files_array;
}


/**
 * createContentFile()
 *
 * @param section is the section the page goes in
 * @param page_id is the id of the page
 *
 * @return the success of the operation
*/
function createContentFile($section, $page_id) {

	if ($section && $page_id) {

		# Create content
		$content = "<" . "? include \"../includes/main.php\"; ?" . ">";

		# Write
		return createFile("../" . $section, $page_id . ".php", $content);

	} else {

		addError("<p>createContentFile(): requires both a section and a page ID to be passed.</p>", 3);

		# Fail
		return false;
	}
}

/**
 * deleteContentFile()
 *
 * @param section is the section the page goes in
 * @param page_id is the id of the page
 *
 * @return the success of the operation
*/
function deleteContentFile($section, $page_id) {

	if ($section && $page_id) {

		return deleteFile("../" . $section, $page_id . ".php");

	} else {

		addError("<p>deleteContentFile(): requires both section and page ID to be passed.</p>", 3);

		# Fail
		return false;
	}
}

/**
 * createFile() creates a text file
 *
 * @param path is the path to where the file should go
 * @param file_name is the file name
 * @param content is the content of the file
 *
 * @return the success of the operation
*/
function createFile($path, $file_name, $content = "") {

	if ($path && $file_name) {

		# Open file
		if (!$handle = @fopen($path . "/" . $file_name, "x+")) {
			addError("<p>createFile(): Cannot open file handler for file:<code>" .$path . "/" . $file_name . "</code></p>", 2);

			# Fail
			return false;

		} else {

			# Attempt to write
			if (fwrite($handle, $content) === false) {
				addError("<p>createFile(): File created, but couldn't be written to:<code>" . $path . "/" . $file_name . "</code></p>", 2);

				# Fail
				return false;
			}
		}

		# Close file
		fclose($handle);

		# OK
		return true;

	} else {

		addError("<p>createFile(): requires both a path and a filename to be passed</p>", 3);

		# Fail
		return false;
	}
}


/**
 * createThumbnail() creates a thumbnail from a passed JPG image path
 *
 * @param image_path is the path to the base image
 * @param base_image is the base image to create a thumbnail for
 * @param output_image is whether to directly output the image (if true), or save it to the thumbnails directory (if false)
 * @param max_width is the maximum width
 * @param max_height is the maximum height
*/
function createThumbnail($image_path = "", $base_image = "", $output_image = false, $max_width = 100, $max_height = 100) {

	# Determine new file path and name
	$thumb_file_name = "thumbnails/" . $base_image;

	# Get size of current image
	$size = getImageSize($image_path . $base_image);

	# If taller than wide
	if ($size[0] < $size[1]) {
		$height = $max_height;
		$width = ($height / $size[1]) * $size[0];
	} else {
		$width = $max_width;
		$height = ($width / $size[0]) * $size[1];
	}

	# Get existing image
	$existing_image = imageCreateFromJPEG($image_path . $base_image);

	# Create thumb image
	$thumb_image = imageCreateTrueColor($width, $height);

	# Copy into new small image
	imageCopyResampled($thumb_image, $existing_image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);

	# Destroy original
	imageDestroy($existing_image);

	# Determine path
	$thumbnail_path = ($output_image) ? "" : $image_path . $thumb_file_name;

	# Save
	if (imageJPEG($thumb_image, $thumbnail_path, 80)) {
		return true;
	} else {
		return false;
	}
}

/**
 * writeLog() writes a log file
 *
 * @param message is the message to log
*/
function writeLog($message = "", $logs_path = "../assets/logs/") {

	if ($message != "") {

		# Create filename
		$filename = date("Ymd") . "-" . date("His") . "-" . rand(100, 200) . ".txt";

		# Open file
		if (!$handle = fopen($logs_path . $filename, "x+")) {
		} else {

			# Attempt to write
			if (fwrite($handle, $message) === FALSE) {
			}
		}

		# Close file
		fclose($handle);
	}
}


# If using modern PHP
if (PHP_VERSION >= 5) {

	# Emulate the old xslt library functions
	function xslt_create() {
		return new XsltProcessor();
	}

	function xslt_process($xsltproc, $xml_arg, $xsl_arg, $xslcontainer = null, $args = null, $params = null) {

		# Start with preparing the arguments
		$xml_arg = str_replace('arg:', '', $xml_arg);
		$xsl_arg = str_replace('arg:', '', $xsl_arg);

		# Create instances of the DomDocument class
		$xml = new DomDocument;
		$xsl = new DomDocument;

		# Load the xml document and the xsl template
		$xml->loadXML($args[$xml_arg]);
		$xsl->loadXML($args[$xsl_arg]);

		# Load the xsl template
		$xsltproc->importStyleSheet($xsl);

		# Set parameters when defined
		if ($params) {
			foreach ($params as $param => $value) {
				$xsltproc->setParameter("", $param, $value);
			}
		}

		// Start the transformation
		$processed = $xsltproc->transformToXML($xml);

		// Put the result in a file when specified
		if ($xslcontainer) {
			return @file_put_contents($xslcontainer, $processed);
		} else {
			return $processed;
		}
   }

	function xslt_free($xsltproc) {
		unset($xsltproc);
	}
}
?>